import encode from '../../utils/base64.js';
import request from '../../utils/config.js';
import util from '../../utils/util.js';
// let WXBizDataCrypt = require('../../utils/RdWXBizDataCrypt.js');
const app = getApp()
Page({
  data: {
    animationData: {},
    loading: false,
    avatarUrl: "",
    nickName: "",
    password: "",
    pwdMobileNo: "",
    department: '',
    flagName:"",
    hideDepartment: true,
    departmentList: [],
    loginUserInfo:"",
    jurisdictionList: [],
    showModel:false
  },

  onShow: function (){
    wx.hideShareMenu();
    if (!app.globalData.userInfo) {
      // 获取用户信息
      let _that = this;
      app.getAuthUserInfo((res)=>{
        res.userInfo.nickName = res.userInfo.nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
        app.globalData.userInfo = res.userInfo;
        app.globalData.encryptedData = res.encryptedData;
        app.globalData.iv = res.iv;
        _that.setData({
          nickName: res.userInfo.nickName,
          avatarUrl: res.userInfo.avatarUrl
        });
        _that.getOpenid(_that);
      },(res)=>{
        _that.setData({
          showModel: true
        })
      });
    }else{
      console.log('重新进入登录界面')
      this.setData({
        nickName: app.globalData.userInfo.nickName,
        avatarUrl: app.globalData.userInfo.avatarUrl
      });
    }
  },

  /**
 * 生命周期函数--监听页面初次渲染完成
 */
  onReady: function () {
    this.toast = this.selectComponent("#toast");
  },

  //组件授权回调
  _setAuthorization: function (e) {
    let that = this;
    let res = e.detail;
    console.log("res====", res)
    that.setData({
      nickName: res.userInfo.nickName,
      avatarUrl: res.userInfo.avatarUrl
    });
    that.getOpenid(that);
  },

  //下拉重新加载
  onPullDownRefresh: function () {
    if (!app.globalData.userInfo) {
      this.setData({
        showModel: true
      })
    } 
  },

  //获取openid
  getOpenid: (_that) => {
    app.getGlobalOpenid(function (token){
      if (token) {
        //开始校验看token值
        _that.checkToken();
      } else {
        wx.hideLoading();
      }
    });
  },
  
  //检验token值
  checkToken: function () {
    let _that = this;
    app.checkGlobalToken(function (res) {
       _that.setData({
         loginUserInfo: res.loginUserInfo,
        });
       let tempList = res.tempList;
       let flagName = res.flagName;
       let jurisdiction =  res.jurisdiction;
       let roleQuanxian = res.roleQuanxian;
       if (tempList.length == 0) {
         wx.showModal({
           title: '对不起',
           content: '您的权限不足',
           confirmText: "知道了",
           showCancel: false,
           success: function (res) {
             if (res.confirm) {
             } else if (res.cancel) {
             }
           }
         })
         return;
       }

       //存储部门列表
       wx.setStorageSync("departmentList", JSON.stringify(tempList));
       //校验上次记住的部门权限是否还存在
       if (jurisdiction.indexOf(roleQuanxian) < 0) {
         wx.showModal({
           title: '对不起',
           content: "您的" + department + "权限不足,请重新选择部门",
           confirmText: "知道了",
           showCancel: false,
           success: function (res) {
             if (res.confirm) {
             } else if (res.cancel) {
             }
           }
         })
         _that.setData({
           jurisdictionList: tempList,
           hideDepartment: false
         });
         return;
       }

       if (flagName) {
         _that.setData({
           pwdMobileNo: res.loginUserInfo.loginId,
           password: '111111'
         });
       }

       if (flagName == "enforce" || flagName == 'lawsuit') {
         wx.hideLoading();
         wx.redirectTo({
           url: '../syIndex/syIndex?flagName=' + flagName
         })
       } else if (flagName == "lawsuitInvest") {
         wx.hideLoading();
         wx.redirectTo({
           url: '../SuSong/ssIndex/ssIndex?flagName=' + flagName
         })
       } else if (flagName == "nonLitigation") {
         wx.hideLoading();
         wx.redirectTo({
           url: '../../pages/FeiSu/fsIndex/fsIndex?flagName=' + flagName
         })
       } else if (flagName == "caseTrack") {
         wx.hideLoading();
         wx.redirectTo({
           url: '../../pages/Case/caseIndex/caseIndex?flagName=' + flagName
         })
       }
    },function(res){
      wx.showModal({
        title: '系统提示',
        content: 'token值校验失败',
        confirmText: '确定',
        confirmColor: '#35ca14',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          }
        }
      })
    });
  },

  onLoad: function () {
    
  },

  //获取密码输入手机号的值
  pwdPhone: function (e) {
    var telPhone = e.detail.value;
    this.setData({
      pwdMobileNo: e.detail.value
    })
  },

  //获取密码值
  pwdSave: function (e) {
    var pwd = e.detail.value;
    this.setData({
      password: e.detail.value
    })
  },

  // 验证码请求成功  点击保存
  submit: function () {
    this.passwordFun();
  },

  //获取部门
  selectDpt: function(e){
    let flagName = e.currentTarget.dataset.type;
    let dptn = e.currentTarget.dataset.dptn;
    this.setData({
      department: dptn,
      flagName: flagName,
    });
    wx.setStorageSync("flagName", flagName);
    if (flagName == "enforce" || flagName == 'lawsuit') {
      wx.redirectTo({
        url: '../syIndex/syIndex?flagName=' + flagName
      })
    } else if (flagName == "lawsuitInvest") {
      wx.redirectTo({
        url: '../SuSong/ssIndex/ssIndex?flagName=' + flagName
      })
    } else if (flagName == "nonLitigation") {
      wx.redirectTo({
        url: '../../pages/FeiSu/fsIndex/fsIndex?flagName=' + flagName
      })
    } else if (flagName == "caseTrack") {
      wx.redirectTo({
        url: '../../pages/Case/caseIndex/caseIndex?flagName=' + flagName
      })
    }
  },

  //密码登录
  passwordFun: function () {
    var telPhone = this.data.pwdMobileNo;
    var password = this.data.password;
    if (!telPhone) {
      this.showErrorMsg("请输入您的用户名");
      return
    } else if (!this.data.password) {
      if (!password) {
        this.showErrorMsg("请输入您的密码");
        return
      }
    }
    this.setData({
      loading: true
    });
    let bodyInfo = {
      loginId: telPhone,
      password: password,
      openid: app.globalData.openid,
      unionid: app.globalData.unionid
    }
    let _that = this;
    request.requestPostMis_api("token", bodyInfo, (res) => {
      wx.hideLoading();
      _that.setData({
        loading: false
      });
      console.log("密码登录成功=", res)

      if (res.data.isSuccess == "F") {
        _that.showErrorMsg(res.data.error);
      } else {
        //开始保存数据
        wx.setStorageSync("token", res.data.token);
        wx.setStorageSync("loginId", res.data.operInfoVo.loginId);

        //获取权限
        let jurisdiction = res.data.operInfoVo.roles;
        let tempList = new Array();
        if (jurisdiction.indexOf("ROLE_CustomInfoQuery") != -1) {
          tempList.push({ name: '客户开发', flagName: "lawsuitInvest", selected: false });
        }
        if (jurisdiction.indexOf("ROLE_CaseQuery") != -1) {
          tempList.push({ name: '案件跟踪', flagName: "caseTrack", selected: false });
        }
        if (jurisdiction.indexOf("ROLE_LawsuitStepRecordQuery") != -1) {
          tempList.push({ name: '诉讼跟踪', flagName: "lawsuit",selected: false });
        }
        if (jurisdiction.indexOf("ROLE_StepRecordQuery") != -1) {
          tempList.push({ name: '执行跟踪', flagName: "enforce", selected: false });
        }
        if (jurisdiction.indexOf("ROLE_ProjectQuery") != -1) {
          tempList.push({ name: '非诉项目', flagName: "nonLitigation", selected: false });
        }
        if (tempList.length == 0) {
          wx.showModal({
            title: '对不起',
            content: '您的权限不足',
            confirmText: "知道了",
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
              } else if (res.cancel) {
              }
            }
          })
          return;
        }

        //存储部门列表
        wx.setStorageSync("departmentList", JSON.stringify(tempList));

        //开始保存数据
        wx.setStorageSync("token", res.data.token);
        wx.setStorageSync("loginId", res.data.operInfoVo.loginId);
        app.globalData.operId = res.data.operId;
        app.globalData.loginUserInfo = res.data.operInfoVo;

        //如果只有一个部门
        if (tempList.length == 1){
          //登录成功之后跳转页面
          // 执行("enforce"), 诉讼("lawsuit"), 市场部("lawsuitInvest")
          wx.setStorageSync("flagName", tempList[0].flagName);
          let flagName = tempList[0].flagName;
          _that.setData({
            department: tempList[0].name,
            flagName: tempList[0].flagName,
          });
          if (flagName == "enforce" || flagName == 'lawsuit') {
            wx.redirectTo({
              url: '../syIndex/syIndex?flagName=' + flagName
            })
          } else if (flagName == "lawsuitInvest") {
            wx.redirectTo({
              url: '../SuSong/ssIndex/ssIndex?flagName=' + flagName
            })
          } else if (flagName == "nonLitigation") {
            wx.redirectTo({
              url: '../../pages/FeiSu/fsIndex/fsIndex?flagName=' + flagName
            })
          } else if (flagName == "caseTrack") {
            wx.redirectTo({
              url: '../../pages/Case/caseIndex/caseIndex?flagName=' + flagName
            })
          }
        }else{
          _that.setData({
            jurisdictionList: tempList,
            hideDepartment: false
          });
        }
      }
    }, (res) => {
      _that.setData({
        loading: false
      });
      console.log("密码登录失败=", res)
    });
  },


  //errorMsg显示
  showErrorMsg: function (msg) {
    this.setData({
      errorMsg: msg
    });
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    })
    this.animation = animation
    animation.translateY(26).step()
    this.setData({
      animationData: animation.export()
    })
    setTimeout(function () {
      animation.translateY(-26).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 2000)
  },
})